<?php


namespace app\shop\service\chat;


use app\shop\common\consts\RedisKey;
use app\shop\model\chat\GroupUserModel;
use app\shop\model\user\ChatUserModel;
use app\shop\model\user\MessageModel;
use app\shop\model\user\UserModel;
use app\shop\service\BaseService;
use app\shop\service\until\FileService;
use think\facade\Cache;

class ChatGroupUserService extends BaseService
{

    public static function getInstance()
    {
        // TODO: Implement getInstance() method.
    }

    public function __construct()
    {
        $this->model = new GroupUserModel();
    }

    /**
     * 建立群聊
     * @param $userId
     * @param $orderId
     * @param $orderName
     * @return bool
     * @throws \Exception
     */
    public function createGroup($userId, $orderId, $orderName)
    {
        // 建立群聊
        $chatSign = generate_chat_sign($userId, 0, $orderId);

        $chatUser = new ChatUserModel();
        $chatUser->order_id = $orderId;
        $chatUser->order_name = $orderName;
        $chatUser->title = $orderName;
        $chatUser->chat_sign = $chatSign;
        $chatUser->save();

        $serviceId = UserModel::where('role_id', 3)->where('join_group', 1)->value('user_id');
        if (!$serviceId) {
            $serviceId = UserModel::where('role_id', 3)->max('user_id');
        }

        $chatUserService = new ChatUserService();
        $chatUserService->joinGroup($chatSign, $userId);
        $chatUserService->joinGroup($chatSign, $serviceId);

        // 群聊
        $groupAvatar = $this->createGroupAvatar($chatSign);
        if ($groupAvatar) {
            ChatUserModel::update(['avatar' => $groupAvatar], ['chat_sign' => $chatSign]);
        }

        // 通知客户
        $content = '<p>您的订单' . $orderName . '已创建！</p>';
        $messageModel = new MessageModel();
        $messageModel->id = generateUuidV4();
        $messageModel->from_user = $serviceId;
        $messageModel->from_user_role_id = 3;
        $messageModel->content = $content;
        $messageModel->chat_sign = $chatSign;
        $messageModel->type = 'text';
        $messageModel->trans_msg = [];
        $messageModel->save();

        $chatVoiceService = new ChatVoiceService();
        $chatVoiceService->setLastMessageToRedis($chatSign, $messageModel->msg_id, $content, 'text', $serviceId, '');
        return true;
    }

    /**
     * 生成群聊头像
     * @param $chatSign
     * @return bool|string
     * @throws \Exception
     */
    public function createGroupAvatar($chatSign)
    {
        try {
            $groupUserIdArr = $this->model->where('chat_sign', $chatSign)->column('user_id');
            $userList = UserModel::whereIn('user_id', $groupUserIdArr)->limit(9)->select()->toArray();

            $imgList = [];
            $dirPath = app()->getRootPath() . 'public/temp';
            foreach ($userList as $k => $v) {
                if ($v['avatar']) {
                    $imgList[] = avatarUrl($v['avatar'], $v['realname'], $v['user_id']);
                } else {
                    $imgList[] = circleAvatar($v['realname'], 80, $v['user_id'], 1, $dirPath);
                }
            }
            $path = $dirPath . '/' . $chatSign . '.jpg';

            $res = getGroupAvatar($imgList, 1, $path);
            // 上传到oss
            if ($res) {
                $file = new FileService();
                $res = $file->upload($chatSign, [], $path, '', false);
                return $res['src'];
            }
            return '';
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}